'use client';

import React from 'react';
import ReactMarkdown from 'react-markdown';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Copy, RotateCcw } from 'lucide-react';
import { ChatMessage as ChatMessageType } from '@/types/fetch';
import { useChatContext } from '@/contexts/ChatContext';
import { AvatarImage } from '@radix-ui/react-avatar';

interface ChatMessageProps {
  message: ChatMessageType;
  onCopy?: (content: string) => void;
  onRegenerate?: (messageId: string) => void;
  showActions?: boolean;
}

export function ChatMessage({
  message,
  onCopy,
  onRegenerate,
  showActions = true,
}: ChatMessageProps) {
  const { contentDetail } = useChatContext();
  const isUser = message.role === 'user';

  // 调试日志
  if (message.role === 'assistant' && message.isGenerating) {
    console.log(`ChatMessage渲染: AI消息 ${message.id} 正在生成, isGenerating=${message.isGenerating}`);
  }
  const isAssistant = message.role === 'assistant';

  const handleCopy = () => {
    if (onCopy) {
      onCopy(message.content);
    } else {
      navigator.clipboard.writeText(message.content);
    }
  };

  const handleRegenerate = () => {
    if (onRegenerate) {
      onRegenerate(message.id);
    }
  };



  return (
    <div className={`flex gap-3 ${isUser ? 'justify-end' : 'justify-start'} group`}>
      {/* AI头像 */}
      {isAssistant && (
        <Avatar className="w-8 h-8  flex-shrink-0 border-1 border-gray-300">
          {contentDetail?.cover?.url ? (
            <AvatarImage src={contentDetail.cover.url} alt={contentDetail.title} />
          ) : (
            <AvatarFallback className="bg-gradient-to-r from-blue-500 to-blue-600 text-white text-sm">
              🤖
            </AvatarFallback>
          )}
        </Avatar>
      )}

      <div className={`flex flex-col ${isUser ? 'items-end' : 'items-start'} max-w-[85%] sm:max-w-xs md:max-w-md lg:max-w-lg`}>
        {/* 消息气泡 */}
        <div
          className={`px-4 py-3 rounded-2xl relative ${
            isUser
              ? 'bg-blue-500 text-white shadow-md'
              : 'bg-white border border-blue-200 text-gray-900 shadow-sm'
          }`}
        >
          {/* 生成中的动画效果 */}
          {message.isGenerating && (
            <div className="absolute inset-0 bg-blue-50 rounded-2xl animate-pulse opacity-50"></div>
          )}
          
          {/* 消息内容 */}
          <div className="text-sm leading-relaxed relative z-10">
            {isAssistant ? (
              <ReactMarkdown
                components={{
                  // 自定义样式
                  h1: ({ children }) => <h1 className="text-lg font-bold mb-2 text-gray-900">{children}</h1>,
                  h2: ({ children }) => <h2 className="text-base font-semibold mb-2 text-gray-900">{children}</h2>,
                  h3: ({ children }) => <h3 className="text-base font-semibold mb-1 text-gray-900">{children}</h3>,
                  p: ({ children }) => <p className="mb-2 last:mb-0">{children}</p>,
                  ul: ({ children }) => <ul className="list-disc list-inside mb-2 space-y-1">{children}</ul>,
                  ol: ({ children }) => <ol className="list-decimal list-inside mb-2 space-y-1">{children}</ol>,
                  li: ({ children }) => <li className="text-sm">{children}</li>,
                  code: ({ children, className }) => {
                    const isInline = !className;
                    return isInline ? (
                      <code className="bg-gray-100 px-1 py-0.5 rounded text-xs font-mono">{children}</code>
                    ) : (
                      <pre className="bg-gray-100 p-2 rounded text-xs font-mono overflow-x-auto mb-2">
                        <code>{children}</code>
                      </pre>
                    );
                  },
                  blockquote: ({ children }) => (
                    <blockquote className="border-l-4 border-blue-200 pl-3 py-1 bg-blue-50 rounded-r mb-2">
                      {children}
                    </blockquote>
                  ),
                  strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
                  em: ({ children }) => <em className="italic">{children}</em>,
                  a: ({ children, href }) => (
                    <a href={href} className="text-blue-600 hover:text-blue-800 underline" target="_blank" rel="noopener noreferrer">
                      {children}
                    </a>
                  ),
                }}
              >
                {message.content}
              </ReactMarkdown>
            ) : (
              <div className="whitespace-pre-wrap">{message.content}</div>
            )}
          </div>
          
          {/* 生成中指示器 */}
          {message.isGenerating && (
            <div className="flex items-center gap-1 mt-2">
              <div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce"></div>
              <div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
              <div className="w-2 h-2 bg-blue-500 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
            </div>
          )}
          
          {/* 时间戳 */}
          <div className={`text-xs mt-2 ${
            isUser ? 'text-blue-100' : 'text-blue-500'
          }`}>
            {message.timestamp.toLocaleTimeString([], {
              hour: '2-digit',
              minute: '2-digit'
            })}
          </div>
        </div>

        {/* 消息操作按钮 */}
        {showActions && !message.isGenerating && (
          <div className={`flex items-center gap-1 mt-2 opacity-0 group-hover:opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity ${
            isUser ? 'flex-row-reverse' : 'flex-row'
          }`}>
            {/* 复制按钮 */}
            <Button
              variant="ghost"
              size="sm"
              onClick={handleCopy}
              className="h-6 w-6 p-0 text-gray-400 hover:text-gray-600"
              title="复制消息"
            >
              <Copy className="w-3 h-3" />
            </Button>

            {/* AI消息的额外操作 */}
            {isAssistant && (
              <>


                {/* 重新生成按钮 */}
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleRegenerate}
                  className="h-6 w-6 p-0 text-gray-400 hover:text-blue-600"
                  title="重新生成"
                >
                  <RotateCcw className="w-3 h-3" />
                </Button>
              </>
            )}
          </div>
        )}
      </div>

      {/* 用户头像 */}
      {isUser && (
        <Avatar className="w-8 h-8  flex-shrink-0 border-1 border-gray-300">
          <AvatarFallback className=" text-white text-sm">
            👤
          </AvatarFallback>
        </Avatar>
      )}
    </div>
  );
}

// 消息列表组件
interface ChatMessageListProps {
  messages: ChatMessageType[];
  onCopy?: (content: string) => void;
  onRegenerate?: (messageId: string) => void;
  showActions?: boolean;
  isGenerating?: boolean;
}

export function ChatMessageList({
  messages,
  onCopy,
  onRegenerate,
  showActions = true,
  isGenerating = false,

}: ChatMessageListProps) {
  // const { isGenerating } = useChatContext();
  return (
    <>
      {messages.map((message, index) => (
        <ChatMessage
          key={message.id || `msg-${index}`}
          message={message}
          onCopy={onCopy}
          onRegenerate={onRegenerate}
          showActions={showActions}
        />
      ))}
    </>
  );
}
